// -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
//   File Name: qjs_event.cpp
// Description: Bindings for Event
//      Author: Ziming Li
//     Created: 2022-04-23
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#include "./qjs_bindings.h"

#include "blinkit/blink/renderer/bindings/core/qjs/qjs.h"
#include "blinkit/blink/renderer/bindings/core/qjs/qjs_c_function_list_entries.h"
#include "blinkit/blink/renderer/bindings/core/script_controller.h"
#include "blinkit/blink/renderer/core/events/Event.h"

namespace BlinKit {
namespace qjs {

/**
 * https://developer.mozilla.org/en-US/docs/Web/API/Event
 */

static JSValue GetCurrentTarget(JSContext *ctx, JSValueConst thisVal)
{
    Event *event = ScriptWrappable::Cast<Event>(thisVal);
    return ScriptController::From(ctx)->WrapEventTarget(event->currentTarget());
}

static JSValue GetTarget(JSContext *ctx, JSValueConst thisVal)
{
    Event *event = ScriptWrappable::Cast<Event>(thisVal);
    return ScriptController::From(ctx)->WrapEventTarget(event->target());
}

static JSValue GetTimeStamp(JSContext *ctx, JSValueConst thisVal)
{
    Event *event = ScriptWrappable::Cast<Event>(thisVal);
    return JS_NewInt64(ctx, event->createTime());
}

static JSValue GetType(JSContext *ctx, JSValueConst thisVal)
{
    Event *event = ScriptWrappable::Cast<Event>(thisVal);
    return WrapString(ctx, event->type());
}

static JSValue PreventDefault(JSContext *ctx, JSValueConst thisVal, int argc, JSValueConst *argv)
{
    Event *event = ScriptWrappable::Cast<Event>(thisVal);
    event->preventDefault();
    return JS_UNDEFINED;
}

JSValue CreateEventPrototype(JSContext *ctx)
{
    static const JSCFunctionListEntry Funcs[] = {
        CGetSetEntry("currentTarget", GetCurrentTarget, nullptr),
        CFunctionEntry("preventDefault", 0, PreventDefault),
        CGetSetEntry("target", GetTarget, nullptr),
        CGetSetEntry("timeStamp", GetTimeStamp, nullptr),
        CGetSetEntry(Strings::Type, GetType, nullptr)
    };

    JSValue ret = JS_NewObject(ctx);
    JS_SetPropertyFunctionList(ctx, ret, Funcs, std::size(Funcs));
    return ret;
}

} // namespace qjs
} // namespace BlinKit
